//
//  ChatView.m
//  AoJi
//
//  Created by IMacLife on 15/2/26.
//  Copyright (c) 2015年 xuanheng. All rights reserved.
//

#import "ChatView.h"

@implementation ChatView

-(instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self viewDidLoad];
        [self loadView];
        
    }
    return self;
}

-(void)viewDidLoad
{
    //通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillAppear:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillDisappear:) name:UIKeyboardWillHideNotification object:nil];
}

-(void)loadView
{
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, Mainwidth-40, MainHeight-104) style:UITableViewStylePlain];
    _tableView.delegate=self;
    _tableView.dataSource=self;
    [self addSubview:_tableView];
    
    
    UIView *footerView = [[UIView alloc]init];
    
    chatText = [[UITextView alloc]initWithFrame:CGRectMake(10, 10, 200, 50)];
    chatText.backgroundColor=[UIColor redColor];
    chatText.layer.cornerRadius=5;
    chatText.delegate=self;
    chatText.returnKeyType=UIReturnKeySend;
    [self addSubview:chatText];
    //[footerView addSubview:chatText];
    
    UIImageView *userImg = [[UIImageView alloc]initWithFrame:CGRectMake(220, 10, 50, 50)];
    userImg.layer.cornerRadius = userImg.frame.size.width/2;
    userImg.layer.masksToBounds = YES;
    
    //有头像用头像,没有头像用系统头像
    if ([[NSUserDefaults standardUserDefaults]objectForKey:@"avatar"]) {
        [userImg sd_setImageWithURL:[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]objectForKey:@"avatar"]] placeholderImage:[UIImage imageNamed:@"morentouxiang"]];
    }else{
        userImg.image = [UIImage imageNamed:@"morentouxiang"];
    }
    [self addSubview:userImg];
    //[footerView addSubview:userImg];
    
    //_tableView.tableFooterView=footerView;
}

-(void)loadData
{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"talkerid"]=self.userID;
    param[@"firstid"]=self._id;
    
    
    //http://cent.dsgrd.com/me/dialog?talkerid=<uid>&firstid=<message_id>
    NSString *url = [NSString stringWithFormat:@"me/dialog?talkerid=%@&firstid=%@",self.userID,self._id];
    [YHNetwork getInformationWithReguestType:RequestTypeGet WithParameters:param WithApi:url WhenSuccess:^(NSMutableDictionary *response) {
        NSLog(@"%@",response);
        dataArray = response;
    } WhenFailure:^(NSError *failure) {
        NSLog(@"%@",failure);
    }];
}

#pragma mark  ---------通知键盘
//键盘
-(CGFloat)keyboardEndingFrameHeight:(NSDictionary *)userInfo//计算键盘的高度

{
    
    CGRect keyboardEndingUncorrectedFrame = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey]CGRectValue];
    
    CGRect keyboardEndingFrame = [chatText convertRect:keyboardEndingUncorrectedFrame fromView:nil];
    
    return keyboardEndingFrame.size.height;
    
}

//上面不变,下面向上推
-(void)keyboardWillAppear:(NSNotification *)notification

{
    
    CGRect currentFrame = self.frame;
    
    CGFloat change = [self keyboardEndingFrameHeight:[notification userInfo]];
    
    currentFrame.size.height = self.frame.size.height - change ;
    
    self.frame = currentFrame;
    
}

-(void)keyboardWillDisappear:(NSNotification *)notification

{
    
    CGRect currentFrame = self.frame;
    
    CGFloat change = [self keyboardEndingFrameHeight:[notification userInfo]];
    
    currentFrame.size.height = currentFrame.size.height + change ;
    
    self.frame = currentFrame;
    
}

#pragma mark   --------------   UITextViewDelegate
/**
 *  点sent 收键盘 发送消息
 */
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"]) {
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        param[@"receiver_id"]=self.userID;
        param[@"body"]=chatText.text;
        
        [YHNetwork getInformationWithReguestType:RequestTypePost WithParameters:param WithApi:@"me/dialog/send" WhenSuccess:^(NSMutableDictionary *response) {
            NSLog(@"%@",response);
            dict = response;
            
            //long 类型强转一下
            if (((NSNumber*)dict[@"code"]).intValue == 0) {
                [chatText resignFirstResponder];
                textView.text=nil;
            }else{
                NSLog(@"%@",dict[@"message"]);
                UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:dict[@"message"] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alertView show];
            }
            
        } WhenFailure:^(NSError *failure) {
            NSLog(@"%@",failure);
        }];
        return NO;
    }
    return YES;
}

-(void)textViewDidEndEditing:(UITextView *)textView
{
    chatText.text=nil;
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [chatText resignFirstResponder];
}

#pragma mark  -------------UITableViewDelegate
//一个分区显示多少行
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return dataArray.count;
}


//UITableViewCell
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"cell";
    UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    
    NSDictionary *dic =dataArray[indexPath.row];
    
    
    UIView *cellView = [[UIView alloc]init];
    
    //如果是我发送的头像在左边,别人给我发得头像在右边
    UIImageView *sender = [[UIImageView alloc]initWithFrame:CGRectMake(220, 10, 50, 50)];
    sender.layer.cornerRadius = sender.frame.size.width/2;
    sender.layer.masksToBounds = YES;
    
    //有头像用头像,没有头像用系统头像
    if (dic[@"avatar"]) {
        [sender sd_setImageWithURL:[NSURL URLWithString:dic[@"avatar"]] placeholderImage:[UIImage imageNamed:@"morentouxiang"]];
    }else{
        sender.image = [UIImage imageNamed:@"morentouxiang"];
    }
    [cellView addSubview:sender];
    
    UIView *messageView = [[UIView alloc]initWithFrame:CGRectMake(40, 10, self.frame.size.width-80, 50)];
    UILabel *lab = [[UILabel alloc]initWithFrame:CGRectMake(3, 0, 100, 20)];
    lab.text=@"我";
    [messageView addSubview:lab];
    
    UILabel *timeLab = [[UILabel alloc]initWithFrame:CGRectMake(100, 0, 100, 20)];
    timeLab.text=[self getTime:dic[@"created_at"]];
    [messageView addSubview:timeLab];
    
    UIView *line = [[UIView alloc]initWithFrame:CGRectMake(3, 22, messageView.frame.size.width-6, 1)];
    line.backgroundColor=[Color colorFromHexRGB:@"f0f0f0"];
    [messageView addSubview:line];
    
    UILabel *conter = [[UILabel alloc]initWithFrame:CGRectMake(0, 25, 100, 20)];
    conter.text=dic[@"body"];
    [messageView addSubview:conter];
    
    [cellView addSubview:messageView];
    [cell.contentView addSubview:cellView];
    
    
    
    return cell;
}


//cell行高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 65;
}



@end
